import axios from 'axios'
import {TOKEN_KEY} from "/@/assets/constant.js";

// 处理全部
const request = axios.create({
    headers: {
        'Content-Type': 'application/json;charset=uft-8'
    }
})

request.defaults.baseURL = "http://localhost:8873"

// 处理请求
request.interceptors.request.use(config => {
    const token = localStorage.getItem(TOKEN_KEY)
    if (token) {
        config.headers['Authorization'] = "Bearer " + token
    }
    return config
})

// 处理响应
request.interceptors.response.use(res => {
    let status = res.status;
    let msg = res.data.msg;
    if (status === 401) {
        alert("token过期，即将返回登录")
        // 删除token，路由自己知道验证
        localStorage.removeItem(TOKEN_KEY)
    } else if (status !== 200) {
        alert(msg)
    }
    return res
}, err => {
    console.log(err)
    alert("请求异常，请联系管理员。")
})

export default request
